<?php

namespace app\common\library;

use app\common\model\UserUndeleteTypeData;
use app\common\library\YuUtil;
use think\facade\Config;

use think\db;

class YuUnDeleteType
{
    const VERSION = '6.0.5';

    protected $errorString = '';

    public static $instance ;

    /**
     * @title 单例调用
     * @description 单例调用
     * @author Admin ldy
     * @time 2018/9/25  12:22
     */
    public static function getInstance(){
        if (YuUnDeleteType::$instance == null){
            YuUnDeleteType::$instance = new \app\common\library\YuUnDeleteType;
            return YuUnDeleteType::$instance;
        }else{
            return YuUnDeleteType::$instance;
        }
    }

    public function __construct(){
        //初始化
    }

    public function setErrorString($msg){
        $this->errorString = $msg;
    }

    public function getErrorString(){
        return $this->errorString;
    }

    public static function addUserUnDeleteType($uid,$data){
        $userUnDeleteType = new UserUndeleteTypeData();
        $userUnDeleteType->user_id =$uid;
        $userUnDeleteType->type_id_string = json_encode($data);
        $re = $userUnDeleteType->save();
        if ($re){
            return new ReSuccess('数据处理成功！',$userUnDeleteType);
        }else{
            return new ReFail(ErrorType::ACTION_FAILED);
        }
    }

    public static function getUserUnDeleteType($uid){
        $where=array(
            'user_id'=>$uid,
        );
        $userUnDeleteType = UserUndeleteTypeData::where($where)->find();
        if ($userUnDeleteType){
            return new ReSuccess('数据处理成功！',json_decode($userUnDeleteType->type_id_string));
        }else{
            return new ReFail(ErrorType::ACTION_FAILED);
        }
    }

    /**
     * @title 获取微信收藏的目录id
     * @description 获取微信收藏的目录id，依据用户id
     * @author Admin ldy
     * @param name:$uid  type:string require:1 default:1 desc:
     * @return ReFail|ReSuccess
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     * @time 2018/10/31  11:44
     */
    public static function getUserWxTypeIdByUserId($uid){
        $where = array(
            'uid'=>$uid,
            'desc' => 'wx',
        );
        $user_wx_type_id = Db::table('scj_type')->field('id')->where($where)->find();
        if ($user_wx_type_id){
            return new ReSuccess('数据处理成功！',$user_wx_type_id);
        }else{
            return new ReFail(ErrorType::GET_DATA_FAILED);
        }
    }

    /**
     * @title 获取浏览器收藏的目录id
     * @description 获取浏览器收藏的目录id，依据用户id
     * @author Admin ldy
     * @param name:$uid  type:string require:1 default:1 desc:
     * @return ReFail|ReSuccess
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     * @time 2018/10/31  11:44
     */
    public static function getUserBrowserTypeIdByUserId($uid){
        $where = array(
            'uid'=>$uid,
            'desc' => 'browser',
        );
        $type_id = Db::table('scj_type')->field('id')->where($where)->find();
        if ($type_id){
            return new ReSuccess('数据处理成功！',$type_id);
        }else{
            return new ReFail(ErrorType::GET_DATA_FAILED);
        }
    }

    /**
     * @title 检查是否是第一次操作用户的文件夹
     * @description 检查是否是第一次操作用户的文件夹
     * @author Admin ldy
     * @param name:$uid  type:string require:1 default:1 desc:
     * @time 2018/10/31  12:04
     * @return ReFail|ReSuccess
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public static function checkFirstTypeByUid($uid){
        $where = array(
            'uid'=>$uid,
            'name' => 'root_'.$uid,
        );
        $my_base_type_id = Db::table('scj_type')->field('id')->where($where)->find();
        if (!$my_base_type_id){
            //如果找不到类型，说明很有可能是第一次查询，这个时候，需要给用户添加一个基本数据,初始化用户数据
            $undeleteArr = array();
            //第一步建立根目录
            $type =new \app\common\model\Type();
            $type->name = 'root_'.$uid;
            $type->uid = $uid;
            $type->pid = 0;
            $re = $type->save();
            //获取根目录的id
            $base_type_id = $type->id;
            array_push($undeleteArr,$base_type_id);
            //新建根目录下面的一个欢迎目录
            $type =new \app\common\model\Type();
            $type->name = '微信收藏';
            $type->uid = $uid;
            $type->pid = $base_type_id;
            $type->desc = 'wx';
            $re2 = $type->save();
            array_push($undeleteArr,$type->id);
            //新建根目录下面的一个欢迎目录2
            $type =new \app\common\model\Type();
            $type->name = '导入的url在这里';
            $type->uid = $uid;
            $type->desc = 'browser';
            $type->pid = $base_type_id;
            $re3 = $type->save();
            array_push($undeleteArr,$type->id);
            if ($re&&$re2&&$re3){
                //设置用户不能删除这几条数据，异步的
                \app\common\library\YuActivity::addUnDeleteTypeRuleForUserInBackGround($uid,$undeleteArr);
                return new ReSuccess('数据处理成功！',$base_type_id);
            }else{
                return new ReFail(ErrorType::ACTION_FAILED);
            }
        }else{
            return new ReSuccess('数据处理成功！',$my_base_type_id);
        }
    }

    /**
     * @title 递归新增用户导入的数据
     * @description 递归新增用户导入的数据
     * @author Admin ldy
     * @param name:$uid  type:string require:1 default:1 desc:用户id
     * @param name:$arr  type:string require:1 default:1 desc:子目录数组
     * @time 2018/11/7  10:10
     * @return ReFail
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public static function getFolder($uid,$arr,$typeid,$level=0){
        $switch = Config::get('scj.status_upload_user_data');
        if ($switch=='0'){
            return new ReFail(ErrorType::NO_ADMIN);
        }
        $len = count($arr);
//        kh('arr-len: '.$len);
        for ($i = 0;$i<$len;$i++){
            if (!empty(YuUtil::getStringByKey($i,$arr))){
//                kh('level: '.$level);

                $flodername = $arr[$i]['flodername'];
                $url_list = $arr[$i]['url_list'];
                $children = $arr[$i]['floder_children'];

                $re = YuUnDeleteType::addType($uid,$typeid,$flodername);
                if (!$re->getStatus()){
                    return new ReFail(ErrorType::ACTION_FAILED,'新增目录失败！YuUnDeleteType::addType');
                }
                $tid = $re->getData();
//                kh('$tid: '.$tid);
                $url_list_len = count($url_list);
//                kh('$url_list_len: '.$url_list_len);
                if ($url_list_len>0){
                    for ($j=0;$j<$url_list_len;$j++){
                        if (!empty(YuUtil::getStringByKey($j,$url_list))){

                            $key_word = '浏览器导入';
                            $desc = '浏览器导入（待修改）';
                            $token = '';
                            $option = array(
                                'url'=>$url_list[$j]['href'],
                                'typeid'=>$tid,
                                'nickname'=>$url_list[$j]['name'],
                                'desc'=>$desc,
                                'key_word'=>$key_word,
                                'uid'=>$uid,
                                'token'=>$token,
                            );
//                            kh('addPersonUrlByType: '.$option['url']);
                            $re2 = \app\common\library\YuPerdata::addPersonUrlByType($option,'fast');
                            if (!$re2->getStatus()){
                                return new ReFail(ErrorType::ACTION_FAILED,'新增个人url失败！YuPerdata::addPersonUrlByType');
                            }
                        }
                    }
                }

                //开始递归
                if (count($children)>0){
                    YuUnDeleteType::getFolder($uid,$children,$tid,$level+1);
                }
            }
        }
        return new ReSuccess('数据处理成功！');
    }

    /**
     * @title 新增一条type记录
     * @description 给用户的某个目录，新建一个目录
     * @author Admin ldy
     * @param name:$uid  type:string require:1 default:1 desc:
     * @param name:$typeid  type:string require:1 default:1 desc:
     * @param name:$typename  type:string require:1 default:1 desc:
     * @time 2018/11/7  9:30
     * @return ReFail|ReSuccess
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public static function addType($uid,$typeid,$typename){
        $con = array(
            'name'=>$typename,
            'pid' =>$typeid,
        );
        $isTypeExist =Db::table('scj_type')->where($con)->find();
        if ($isTypeExist){
            //同一目录下面，应该命名不同
            return new ReFail(ErrorType::DATA_EXIST);
        }
        //增加的是下级，所以，当前id变成新增加的类型的父级id
        $pid = $typeid;
        $typeModel = new \app\common\model\Type();
        $typeModel->pid = $pid;
        $typeModel->uid = $uid;
        $typeModel->name = $typename;
        $re = $typeModel->save();
        if ($re){
//            kh('addType-id: '.$typeModel->id);
            return new ReSuccess('新增一条记录成功！',$typeModel->id);
        }else{
            return new ReFail(ErrorType::ACTION_FAILED);
        }
    }


}
